﻿using Microsoft.Win32;
using NUnit.Framework;
using System;
using System.Collections;
using System.Collections.Generic;

namespace Api
{
    public class ApiService
    {
        /// <summary>
        /// 进场刷卡  安科对接系统
        /// </summary>
        /// <param name="card_no">卡编号</param>
        /// <param name="brakemachine_no">闸机编号</param>
        /// <returns></returns>
        public static Dictionary<string, object> inSwipeCard(string card_no, string brakemachine_no)
        {

            //判断是否为员工卡
            int flag = BehaviorLogService.getInstance().owner_type(card_no);
            if (flag == 0)
            {
                return getResult(false, "100012", false);
            }

            if (flag == 2)
            { //是员工卡
                return varify_date(card_no);
                //return getResult(true, "", true);
            }

            //判断当前卡的状态是否正常
            if (is_in_out(card_no) == "out")
            {
                return varify_card_in(card_no, brakemachine_no);
            }
            else
            {//当前卡 未按正常程序退出闸机
                BehaviorLogService.getInstance().addInBrackmachineBehavior(card_no, brakemachine_no, 2, "100003");
                return getResult(false, "100003", false);
            }
        }
        /// <summary> 
        /// 出场刷卡
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static Dictionary<string, object> outSwipeCard(string card_no, string brakemachine_no)
        {
            //判断是否为员工卡
            int flag = BehaviorLogService.getInstance().owner_type(card_no);
            Console.WriteLine("flag:" + flag);
            if (flag == 2)
            { //是员工卡
                return varify_date(card_no);
                //return getResult(true, "", true);
            }
            if (flag == 0)
            {
                return getResult(false, "100012", false);
            }
            //判断当前卡的状态是否正常
            if (is_in_out(card_no) == "in")
            {
                return varify_card_out(card_no, brakemachine_no);
            }
            else
            {//当前卡 未按正常程序退出闸机
                BehaviorLogService.getInstance().addOutBrackmachineBehavior(card_no, brakemachine_no, 2, "100004");
                return getResult(false, "100004", false);
            }
        }

        /// <summary>
        /// 刷指纹结果回调
        /// </summary>
        /// <param name="card_no">卡编号</param>
        /// <param name="brakemachine_no">闸机编号</param>
        /// <param name="flag">比对成功或失败</param>
        public static void swipeFingerPrintResult(string card_no, bool flag, string brakemachine_no)
        {
            if (flag == true)
            { // 指纹比对成功
                BehaviorLogService.getInstance().addSwipeFingerBehavior(card_no, 1, "", brakemachine_no);//刷指纹记录
                BehaviorLogService.getInstance().addInBrackmachineBehavior(card_no, brakemachine_no, 1, "");//卡闸机记录

                object card = CardService.getInstance().findByCardNo(card_no);

                Hashtable item = (Hashtable)card;
                string now_date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                string in_surplus_limt = item["in_surplus_limt"].ToString();// 剩余进场次数限制
                string in_varifycation = item["in_varifycation"].ToString();// 入场指纹验证
                int surplus = (int)item["surplus"];// 剩余次数

                //卡的剩余次数减一
                bool temp = CardService.getInstance().inSurplusSubAndStatistic(card_no);
                if (temp)
                {
                    surplus = surplus - 1;
                    //注册表写数据
                    string reg_key = GetTimeStamp();
                    string dex_card_no = to_dec_resers(card_no);
                    string reg_value = dex_card_no + ";" + in_surplus_limt + ";" + now_date + ";" + surplus;
                    write(reg_key, reg_value);
                    Console.WriteLine("reg_value" + reg_value);
                }

            }
            else
            { //指纹比对失败
                BehaviorLogService.getInstance().addSwipeFingerBehavior(card_no, 2, "100006", brakemachine_no);
                BehaviorLogService.getInstance().addInBrackmachineBehavior(card_no, brakemachine_no, 2, "100006");//卡闸机记录
            }
        }

        /// <summary>
        /// 刷存储柜子
        /// </summary>
        /// <param name="card_no">卡编号</param>
        public static Dictionary<string, object> swipeLockers(string card_no, string lockers_no)
        {
            //是取 是存  0 没有物品  1有物品
            int in_out = LockersService.getInstance().is_in_out(card_no);
            //存储柜信息
            var lockers = LockersService.getInstance().getLockers(lockers_no);

            // 判断卡是在闸机外面 还是里面
            string card_status = is_in_out(card_no);
            if (card_status == "out")
            {//卡状态不正确
                BehaviorLogService.getInstance().addInBrackmachineBehavior(card_no, lockers_no, 2, "100003");
                return getResult(false, "100003", false);
            }
            else
            {
                if (in_out == 0)
                {   // 说明 要做存的操作

                    if (lockers.status == 1)
                    {//储物柜没有其他人的东西
                        BehaviorLogService.getInstance().addLockersBehavior(card_no, lockers_no, 1, "");
                        //更新储物柜状态
                        LockersService.getInstance().store_update(card_no, lockers_no);
                        return getResult(true, "", true);
                    }
                    else
                    {//储物柜有其他人的东西
                        BehaviorLogService.getInstance().addLockersBehavior(card_no, lockers_no, 2, "100007");
                        return getResult(false, "100007", false);
                    }

                }
                else
                { //说明要做取的操作

                    if (lockers.card_no == card_no)
                    {
                        //新增取物日志
                        BehaviorLogService.getInstance().addUnLockersBehavior(card_no, lockers_no, 1, "");
                        //更新储物柜状态
                        LockersService.getInstance().unstore_update(card_no, lockers_no);
                        return getResult(true, "", true);
                    }
                    else
                    {
                        BehaviorLogService.getInstance().addUnLockersBehavior(card_no, lockers_no, 2, "100008");
                        return getResult(false, "100008", false);
                    }

                }
            }
        }

        /// <summary>
        /// 查询 根据卡号 查询所在 储物柜编号
        /// </summary>
        public static Dictionary<string, object> getLockersByCardNo(string card_no)
        {
            var lockers = LockersService.getInstance().getLockersByCardNo(card_no);
            if (lockers == null)
            {
                return getResult(false, "100010", false);
            }
            else
            {
                return getResult(true, lockers.num, true);
            }
        }

        /// <summary>
        /// 储柜子 信息同步
        /// </summary>
        /// <param name="obj">自定义数据</param>
        public static void lockersSyn(object obj)
        {
            //暂时不用
        }


        ///////////////////////////////////////////////以下是业务逻辑/////////////////////////////////////////
        /// <summary>
        ///用户结果集合 
        /// </summary>
        /// <param name="flag">成功或失败</param>
        /// <param name="data">附带信息</param>
        /// <param name="is_open">是否开启</param>
        /// <returns></returns>
        public static Dictionary<string, object> getResult(bool flag, string data, bool is_open)
        {
            //用户返回结果集
            Dictionary<string, object> result = new Dictionary<string, object>();
            result.Add("flag", flag);
            result.Add("data", data);
            result.Add("is_open", is_open);
            return result;
        }
        /// <summary>
        /// 进场 验卡
        /// </summary>
        /// <param name="card_no"></param>
        /// <returns></returns>
        public static Dictionary<string, object> varify_card_in(string card_no, string brakemachine_no)
        {
            object card = CardService.getInstance().findByCardNo(card_no);
            if (card == null)
            { // 卡为空
                return getResult(false, "100000", false);
            }
            Hashtable item = (Hashtable)card;
            string now_date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            string effect_date = Convert.ToDateTime(item["effect_date"].ToString()).ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);// 有效截至时间
            string start_date = Convert.ToDateTime(item["start_date"].ToString()).ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);// 有效开始时间
            string in_surplus_limt = item["in_surplus_limt"].ToString();// 剩余进场次数限制
            string in_varifycation = item["in_varifycation"].ToString();// 入场指纹验证
            int surplus = (int)item["surplus"];// 剩余次数
            int in_surplus_sub = (int)item["in_surplus_sub"];// 剩余次数减一  
            string fingerprint = item["fingerprint"].ToString();// 指纹数据
            int status = (int)item["status"];// 当前会员是否有效
            int free_finger = (int)item["free_finger"];// 年卡是否免指纹   //0 否 1验卡
            int free_finger_varify = (int)item["free_finger_varify"];// 前台是否验卡  0否 1验卡
            string free_finger_varify_time = item["free_finger_varify_time"].ToString();// 上次验证通过时间

            if (status != 1)
            {   //会员状态是否有效                 
                BehaviorLogService.getInstance().addInBrackmachineBehavior(card_no, brakemachine_no, 2, "100013");
                return getResult(false, "100013", false);
            }

            if (effect_date.CompareTo(now_date) < 0)
            { // 卡片过期
                //记录日志
                BehaviorLogService.getInstance().addInBrackmachineBehavior(card_no, brakemachine_no, 2, "100001");
                return getResult(false, "100001", false);
            }
            if (start_date.CompareTo(now_date) > 0)
            { // 卡片还未激活
                //记录日志
                BehaviorLogService.getInstance().addInBrackmachineBehavior(card_no, brakemachine_no, 2, "100014");
                return getResult(false, "100014", false);
            }

            if (in_varifycation == "1")
            {// 入场指纹验证
                if (free_finger == 1)
                { //免指纹
                    if (free_finger_varify == 1)
                    { //前台验证通过 有效时间内第一次验证
                        //设置
                        BehaviorLogService.getInstance().setFingerFree(card_no);
                    }
                    else
                    {
                        Console.WriteLine(free_finger_varify_time);
                        //最近一次验证是否过期                       
                        string varify_time = DateTime.Parse(free_finger_varify_time).AddMinutes(CardService.getInstance().get_pvalue(3)).ToString("yyyy-MM-dd HH:mm:ss");
                        if (now_date.CompareTo(varify_time) < 0)
                        { //没过期

                        }
                        else
                        {
                            //没有去前台验证卡
                            BehaviorLogService.getInstance().addInBrackmachineBehavior(card_no, brakemachine_no, 2, "100015");
                            return getResult(false, "100015", false);
                        }

                    }
                }
                else
                {// 不免指纹

                    if (fingerprint == "" || fingerprint.Length < 20)
                    {// 指纹数据为空
                        BehaviorLogService.getInstance().addInBrackmachineBehavior(card_no, brakemachine_no, 2, "100016");
                        return getResult(false, "100016", false);
                    }
                    if (in_surplus_limt == "1")
                    {// 剩余进场次数验证
                        if (surplus < 1)
                        {
                            //卡的剩余次数减一
                            BehaviorLogService.getInstance().addInBrackmachineBehavior(card_no, brakemachine_no, 2, "100009");
                            return getResult(false, "100009", false);
                        }

                    }
                    return getResult(true, fingerprint, false);
                }
            }
            if (in_surplus_limt == "1")
            {// 剩余进场次数验证
                bool flag = CardService.getInstance().inSurplusSubAndStatistic(card_no);
                if ((surplus < 1) && flag)//需要扣次但是余额不足
                {
                    //卡的剩余次数减一
                    BehaviorLogService.getInstance().addInBrackmachineBehavior(card_no, brakemachine_no, 2, "100009");
                    return getResult(false, "100009", false);
                }
                else
                {
                    //卡的剩余次数减一                
                    if (flag)
                    {//需要扣次
                        surplus = surplus - 1;
                        CardService.getInstance().kouci(card_no);
                        //注册表写数据
                        string reg_key = GetTimeStamp();
                        string dex_card_no = to_dec_resers(card_no);
                        string reg_value = dex_card_no + ";" + in_surplus_limt + ";" + now_date + ";" + surplus;
                        write(reg_key, reg_value);
                        Console.WriteLine("reg_value" + reg_value);
                    }

                }
            }
            // 新增入场行为日志
            BehaviorLogService.getInstance().addInBrackmachineBehavior(card_no, brakemachine_no, 1, "");
            // 验证通过 开启设备
            return getResult(true, "", true);
        }

        public static Dictionary<string, object> varify_date(string card_no)
        {
            // object card = CardService.getInstance().findByCardNo(card_no);

            // Hashtable item = (Hashtable)card;
            // string now_date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            //string effect_date = Convert.ToDateTime(item["effect_date"].ToString()).ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);// 有效截至时间
            //if (effect_date.CompareTo(now_date) < 0)
            // { // 卡片过期
            //     //记录日志             
            //     return getResult(false, "100001", false);
            // }
            // else {
            //     return getResult(true, "", true);
            // }
            return getResult(true, "", true);

        }
        /// <summary>
        /// 出场验证卡
        /// </summary>
        /// <param name="card_no"></param>
        /// <returns></returns>
        public static Dictionary<string, object> varify_card_out(string card_no, string brakemachine_no)
        {
            //object card = CardService.getInstance().findByCardNo(card_no);
            //if (card == null)
            //{ // 卡为空
            //    BehaviorLogService.getInstance().addOutBrackmachineBehavior(card_no, brakemachine_no, 2, "100000");
            //    return getResult(false, "100000", false);
            //}
            BehaviorLogService.getInstance().addOutBrackmachineBehavior(card_no, brakemachine_no, 1, "");
            return getResult(true, "", true);
            //Hashtable item = (Hashtable)card;
            //string now_date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //string effect_date = Convert.ToDateTime(item["effect_date"].ToString()).ToString("yyyy-MM-dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);// 有效截至时间

            //string out_varifycation = item["out_varifycation"].ToString();// 入场指纹验证
            //string fingerprint = item["fingerprint"].ToString();// 指纹数据

            //if (effect_date.CompareTo(now_date) < 0)
            //{ // 卡片过期
            //    BehaviorLogService.getInstance().addOutBrackmachineBehavior(card_no, brakemachine_no, 2, "100001");
            //    return getResult(false, "100001", false);
            //}
            //if (out_varifycation == "1")
            //{// 出场场指纹验证
            //    return getResult(true, fingerprint, false);
            //}
            //持卡人是否在 储物柜存有东西
            //int is_store_things= LockersService.getInstance().is_in_out(card_no);
            //int is_store_things = 0;
            //if (is_store_things == 0)
            //{ // 没有存东西
            //    BehaviorLogService.getInstance().addOutBrackmachineBehavior(card_no, brakemachine_no, 1, "");
            //    return getResult(true,"",true);
            //}
            //else {
            //    BehaviorLogService.getInstance().addOutBrackmachineBehavior(card_no, brakemachine_no, 2, "100005");
            //    return getResult(false, "100005", false);
            //}           

        }

        /// <summary>
        /// 根据卡号判断当前  是在砸机外面还是砸机里面
        /// </summary>
        public static string is_in_out(string card_no)
        {
            int status = CardService.getInstance().lastStatusByCard(card_no);
            if (status == 0 || status == 5)
            {// 当前状态 在闸机外
                return "out";
            }
            else
            {// 当前状态 在闸机内
                return "in";
            }
        }

        /// <summary> 
        /// 设置程序开机启动 
        /// 或取消开机启动 
        /// </summary> 
        /// <param name="started">设置开机启动，或者取消开机启动</param> 
        /// <param name="exeName">注册表中程序的名字</param> 
        /// <param name="path">开机启动的程序路径</param> 
        /// <returns>开启或则停用是否成功</returns> 
        public static bool write(string keys, string value)
        {
            try
            {
                RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Anke\\CheckIn", true);//打开注册表子项 
                if (key == null)//如果该项不存在的话，则创建该子项 
                {
                    key = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Anke\\CheckIn");
                }
                key.SetValue(keys, value);
                key.Close();
            }
            catch (Exception e)
            {
                throw e;
              //  Api.util.LogHelper.WriteLog(typeof(Exception), e.Message + "/r/n" + e.StackTrace);
            }
            return true;
        }
        /// <summary>
        /// 16进制转10进制
        /// </summary>
        /// <returns></returns>
        public static String to_dec_resers(string hex)
        {
            string bit1 = hex.Substring(0, 2);
            string bit2 = hex.Substring(2, 2);
            string bit3 = hex.Substring(4, 2);
            string bit4 = hex.Substring(6, 2);
            Console.WriteLine(hex);
            Console.WriteLine(bit4 + bit3 + bit2 + bit1);
            String result = Convert.ToInt64(bit4 + bit3 + bit2 + bit1, 16) + "";
            return result.PadLeft(10, '0');
        }
        public static string GetTimeStamp()
        {

            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds * 1000) + "";
        }

        [Test]
        public void test1()
        {
            object card = CardService.getInstance().findByCardNo("10000");
            if (card == null)
            { // 卡为空
                getResult(false, "100000", false);
            }
            Hashtable item = (Hashtable)card;
            string now_date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string effect_date = item["effect_date"].ToString();
            if (effect_date.CompareTo(now_date) < 0)
            { // 卡片过期
                // 卡为空
                getResult(false, "100001", false);
            }
        }

    }


}
